package com.atguigu.lease.admin.controller;

import com.atguigu.lease.admin.service.AttrKeyService;
import com.atguigu.lease.admin.service.AttrService;
import com.atguigu.lease.admin.service.AttrValueService;
import com.atguigu.lease.pojo.AttrKey;
import com.atguigu.lease.pojo.AttrValue;
import com.atguigu.lease.result.Result;
import com.atguigu.lease.vo.AttrVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/admin/attr")
@RestController
public class AttrController {
    @Autowired
    private AttrService attrService;
    @Autowired
    private AttrKeyService attrKeyService;
    @Autowired
    private AttrValueService attrValueService;

    @GetMapping("/list")
    public Result<List<AttrVo>> listAttr() {
        List<AttrVo> attrVoList = attrService.listAttr();
        return Result.success(attrVoList);
    }

    @PostMapping("/key/saveOrUpdate")
    private Result saveOrUpdateAttrKey(@RequestBody AttrKey attrKey) {
        attrKeyService.saveOrUpdate(attrKey);
        return Result.success(null);
    }

    @DeleteMapping("/key/deleteById")
    public Result deleteAttrKeyById(@RequestParam(value = "attrKeyId") Long id) {
        long count = attrValueService.count(Wrappers.lambdaQuery(AttrValue.class).eq(AttrValue::getAttrKeyId, id));
        if (count > 0) {
            throw new RuntimeException("请先删除该属性项下的所有属性值");
        }
        attrKeyService.removeById(id);
        return Result.success(null);
    }

    @PostMapping("/value/saveOrUpdate")
    private Result saveOrUpdateAttrValue(@RequestBody AttrValue attrValue) {
        attrValueService.saveOrUpdate(attrValue);
        return Result.success(null);
    }

    @DeleteMapping("/value/deleteById")
    public Result deleteAttrValueById(@RequestParam(value = "id") Long id) {
        attrValueService.removeById(id);
        return Result.success(null);
    }
}
